# 最后修改 2024年10月29日20:01:32
import argparse  
import configparser 
import os  
import fnmatch  
import subprocess  
# 创建对象  
parser = argparse.ArgumentParser(description="")  
config = configparser.ConfigParser() 

# 添加参数  
parser.add_argument("--list", action="store_true",help="列出管理的虚拟机")  
parser.add_argument("--disable", action="store_true", help="关闭自启动虚拟机")   
parser.add_argument("--enable", action="store_true", help="开启自启动虚拟机")  
parser.add_argument("--init", action="store_true", help="初始化环境")  
parser.add_argument("--status", action="store_true", help="状态查看")  

try:
    config.read('./vHost.cfg') 
except UnicodeDecodeError:
         print("读取配置文件失败 不要有中文")
         os._exit(0)

def init(): 
    print(f"查找虚拟机位置中") 
    directory_to_search = 'C:\\Program Files (x86)\\VMware\\VMware Workstation'
    search_pattern = 'vmrun.exe'  # 搜索所有.txt文件  
    found_files = search_files(directory_to_search, search_pattern)  
    for file in found_files:  
        config.set("VMPATH","path",file)
        with open('./vHost.cfg', 'w') as configfile:  
            config.write(configfile)
        return
    print("查找vmware失败 请修改配置文件中的path")
    os._exit(0)
    
def listHost():
    mlist = [] 
    try:
        for i in range(1,100):
            hostString = 'host'+ str(i)
            mlist.append(config['HostList'][hostString])
    except KeyError:
         return mlist

def search_files(directory, pattern):  
    matches = []  
    for root, dirs, files in os.walk(directory):  
        for filename in fnmatch.filter(files, pattern):  
            matches.append(os.path.join(root, filename))  
    return matches  

def getStatus():
     status = config['vHost']['isstart'] 
     print("● vHostServer: ",status) 

# 解析参数  
args = parser.parse_args()  

if args.init:  
   init()
  
path = config['VMPATH']['path']
if path == '""':
   init()

# 检测虚拟机列表
listvm = listHost()

# 使用参数  
if args.status:
     getStatus()
     os._exit(0)
if args.list:  
    print("您的虚拟机列表:")
    for var in listvm:
        print(var)
    os._exit(0)
if args.enable:  
    config.set("vHost","isstart","true")
    with open('./vHost.cfg', 'w') as configfile:  
            config.write(configfile)
    print(f"已设置自动启动虚拟机")  
    os._exit(0)
if args.disable:  
   config.set("vHost","isstart","false")
   with open('./vHost.cfg', 'w') as configfile:  
            config.write(configfile)
   print(f"已设置不自动启动虚拟机")
   os._exit(0)


isstart = config['vHost']['isstart']
if isstart == 'false':
    os._exit(0)

# 启动虚拟机
vmware = config['VMPATH']['path']
for host in listvm:
    subprocess.run([vmware, 'start',host,'nogui'], capture_output=True, text=True) 